package com.yxj.checksystempicture.u;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 */
public class UriUtils {

    /**
     * 将 Uri 转换为 File 对象
     * 注意：对于 Android 7.0 及以上版本，建议使用 content:// Uri 而非 file:// Uri
     * 此方法会在应用的缓存目录创建文件的副本
     */
    public static File uriToFile(Context context, Uri uri) {
        if (uri == null) return null;

        // 处理 file:// Uri
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            return new File(uri.getPath());
        }

        // 处理 content:// Uri
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 尝试从 MediaStore 内容提供者获取文件路径
            String filePath = getFilePathFromContentUri(context, uri);
            if (filePath != null) {
                return new File(filePath);
            }

            // 如果无法获取真实路径（如来自 Google Drive 或其他应用），则创建临时文件
            return createTempFileFromUri(context, uri);
        }

        return null;
    }

    /**
     * 从 content Uri 获取文件路径
     */
    private static String getFilePathFromContentUri(Context context, Uri uri) {
        String filePath = null;
        String[] projection = {MediaStore.Images.Media.DATA};

        try (Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                filePath = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果常规方法失败，则尝试使用文档提供程序方法
        if (filePath == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            filePath = getFilePathFromDocumentUri(context, uri);
        }

        return filePath;
    }

    /**
     * 处理 DocumentProvider 类型的 Uri
     */
    private static String getFilePathFromDocumentUri(Context context, Uri uri) {
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // 处理非主存储情况
                // 注意：这需要额外的存储访问框架权限
                return null;
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.parseLong(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        return null;
    }

    /**
     * 获取数据列的值
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * 判断 Uri 是否为 ExternalStorageProvider
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * 判断 Uri 是否为 DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * 判断 Uri 是否为 MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * 从 Uri 创建临时文件
     */
    private static File createTempFileFromUri(Context context, Uri uri) {
        File tempFile = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            // 创建临时文件
            String fileName = getFileName(context, uri);
            if (fileName == null || fileName.isEmpty()) {
                fileName = "temp_file_" + System.currentTimeMillis();
            }
            tempFile = File.createTempFile(fileName, getFileExtension(context, uri), context.getCacheDir());

            // 复制文件内容
            inputStream = context.getContentResolver().openInputStream(uri);
            outputStream = new FileOutputStream(tempFile);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            // 关闭流
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return tempFile;
    }

    /**
     * 获取文件名
     */
    private static String getFileName(Context context, Uri uri) {
        String fileName = null;
        Cursor cursor = null;

        try {
            ContentResolver contentResolver = context.getContentResolver();
            cursor = contentResolver.query(uri, null, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                int displayNameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
                if (displayNameIndex != -1) {
                    fileName = cursor.getString(displayNameIndex);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return fileName;
    }

    /**
     * 获取文件扩展名
     */
    public static String getFileExtension(Context context, Uri uri) {
        String extension = null;

        try {
            ContentResolver contentResolver = context.getContentResolver();
            String mimeType = contentResolver.getType(uri);

            if (mimeType != null) {
                extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (extension == null || extension.isEmpty()) {
            // 尝试从 Uri 路径获取扩展名
            String path = uri.getPath();
            if (path != null) {
                int dotIndex = path.lastIndexOf('.');
                if (dotIndex > 0) {
                    extension = path.substring(dotIndex + 1);
                }
            }
        }

        return extension != null ? "." + extension : "";
    }
}
